package org.lansir.af.ui;

import java.util.Calendar;
import java.util.Date;

import org.lansir.af.R;
import org.lansir.af.util.Utils;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

/**
 * 活动重复设置界面
 * @author 蓝智宏
 *
 */
public class ActivityRepeat extends Activity {
	// fields
	public static final int SELECT_REPEAT_REQUEST = 201;

	private static final String DATAKEY_TYPE = "RepeatType";
	private static final String DATAKEY_EVERY = "Every";
	private static final String DATAKEY_ENDONDATE = "EndOnDate";

	// fields
	public Utils utils = null;

	// repeat data
	private int iRepeatType = -1;
	private int iRepeatEvery = 0;
	private Calendar calRepeatEnd = Calendar.getInstance();

	// layouts
	private LinearLayout llayAppointmentRepeatEvery = null;
	private LinearLayout llayAppointmentRepeatEndOnDateLabel = null;
	private LinearLayout llayAppointmentRepeatEndOnDate = null;

	// views
	private TextView tvRepeatTitle = null;
	private TextView tvRepeatEveryValue = null;
	private TextView tvRepeatEveryValueType = null;
	private Button btnEndOnDate = null;
	private Button btnRepeatDone = null;

	// repeat buttons
	private Button btnRepeatTypeNone = null;
	private Button btnRepeatTypeDaily = null;
	private Button btnRepeatTypeWeekly = null;
	private Button btnRepeatTypeMonthly = null;
	private Button btnRepeatTypeYearly = null;

	// every value buttons
	private ImageButton btnRepeatEveryDown = null;
	private ImageButton btnRepeatEveryUp = null;

	// methods
	@Override
	public void onCreate(Bundle icicle) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);  
		super.onCreate(icicle);
		setContentView(R.layout.activity_repeat);

		getExtrasData();

		// restore data from freeze state
		if (icicle != null) {
			iRepeatType = icicle.getInt("repeat");
			iRepeatEvery = icicle.getInt("every");
			calRepeatEnd.setTimeInMillis(icicle.getLong("dateEndOn"));
		}

		// initialize base objects
		utils = new Utils(this);

		// initialize views
		initViews();
		initState();
	}

	public void getExtrasData() {
		Bundle bundle = getIntent().getExtras();
		if ((bundle != null) && (bundle.containsKey("EditRepeat"))) {
			iRepeatType = bundle.getInt(DATAKEY_TYPE);
			iRepeatEvery = bundle.getInt(DATAKEY_EVERY);
			calRepeatEnd.setTimeInMillis(bundle.getLong(DATAKEY_ENDONDATE));
		}
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		// save controls state
		outState.putInt("repeat", iRepeatType);
		outState.putInt("every", iRepeatEvery);
		outState.putLong("dateEndOn", calRepeatEnd.getTimeInMillis());
	}


	private void initViews() {
		llayAppointmentRepeatEvery = (LinearLayout) findViewById(R.id.llayAppointmentRepeatEvery);
		llayAppointmentRepeatEndOnDate = (LinearLayout) findViewById(R.id.llayAppointmentRepeatEndOnDate);
		llayAppointmentRepeatEndOnDateLabel = (LinearLayout) findViewById(R.id.llayAppointmentRepeatEndOnDateLabel);

		// repeat buttons
		btnRepeatTypeNone = (Button) findViewById(R.id.btnRepeatTypeNone);
		btnRepeatTypeNone.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				setRepeatType(0);
			}
		});

		btnRepeatTypeDaily = (Button) findViewById(R.id.btnRepeatTypeDaily);
		btnRepeatTypeDaily.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				setRepeatType(1);
			}
		});

		btnRepeatTypeWeekly = (Button) findViewById(R.id.btnRepeatTypeWeekly);
		btnRepeatTypeWeekly.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				setRepeatType(2);
			}
		});

		btnRepeatTypeMonthly = (Button) findViewById(R.id.btnRepeatTypeMonthly);
		btnRepeatTypeMonthly.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				setRepeatType(3);
			}
		});

		btnRepeatTypeYearly = (Button) findViewById(R.id.btnRepeatTypeYearly);
		btnRepeatTypeYearly.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				setRepeatType(4);
			}
		});

		btnEndOnDate = (Button) findViewById(R.id.btnAppointmentEndOnDate);

		btnRepeatDone = (Button) findViewById(R.id.btnRepeatDone);
		btnRepeatDone.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				editDone();
			}
		});

		btnEndOnDate.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Calendar calendar = Calendar.getInstance();
				Date date = new Date();
				// 创建一个Date实例
				calendar.setTime(date);
				// 获得日历中的 year month day
				DatePickerDialog dlg = new DatePickerDialog(
						ActivityRepeat.this, mDateSetListener, calendar
								.get(Calendar.YEAR), calendar
								.get(Calendar.MONTH), calendar
								.get(Calendar.DAY_OF_MONTH));
				// 新建一个DatePickerDialog 构造方法中
				// （设备上下文，OnDateSetListener时间设置监听器，默认年，默认月，默认日）
				dlg.show();
			}
		});

		tvRepeatTitle = (TextView) findViewById(R.id.tvActivityRepeatTitle);
		tvRepeatEveryValue = (TextView) findViewById(R.id.tvRepeatEveryValue);
		tvRepeatEveryValueType = (TextView) findViewById(R.id.tvRepeatEveryValueType);

		btnRepeatEveryDown = (ImageButton) findViewById(R.id.btnRepeatEveryDown);
		btnRepeatEveryDown.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				iRepeatEvery--;
				if (iRepeatEvery < 1)
					iRepeatEvery = 1;
				updateEveryValueView();
			}
		});

		btnRepeatEveryUp = (ImageButton) findViewById(R.id.btnRepeatEveryUp);
		btnRepeatEveryUp.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				iRepeatEvery++;
				if (iRepeatEvery > 30)
					iRepeatEvery = 30;
				updateEveryValueView();
			}
		});
	}

	public void setRepeatType(int iRepeatType) {
		// update global value
		this.iRepeatType = iRepeatType;
		// enable buttons
		btnRepeatTypeNone.setEnabled((iRepeatType != 0));
		btnRepeatTypeDaily.setEnabled((iRepeatType != 1));
		btnRepeatTypeWeekly.setEnabled((iRepeatType != 2));
		btnRepeatTypeMonthly.setEnabled((iRepeatType != 3));
		btnRepeatTypeYearly.setEnabled((iRepeatType != 4));
		String sRepeatValueType = "";
		// 0: None
		Button btn = null;
		if (iRepeatType == 0)
			btn = btnRepeatTypeNone;
		// 1: Daily
		if (iRepeatType == 1){
			btn = btnRepeatTypeDaily;
			sRepeatValueType = utils.getResStr(R.string.strRepeatTypeValueDay);
		}
		// 2: Weekly
		if (iRepeatType == 2){
			btn = btnRepeatTypeWeekly;
			sRepeatValueType = utils.getResStr(R.string.strRepeatTypeValueWeek);
		}
		// 3: Monthly
		if (iRepeatType == 3){
			btn = btnRepeatTypeMonthly;
			sRepeatValueType = utils.getResStr(R.string.strRepeatTypeValueMonth);
		}
		// 4: Yearly
		if (iRepeatType == 4)
			btn = btnRepeatTypeYearly;
		// set focus
		if ((btn != null) && (!btn.isFocused()))
			btn.requestFocus();
		// update title info
		setActivityTitle("");
		tvRepeatEveryValueType.setText(sRepeatValueType);
		if (btn != null)
			setActivityTitle(btn.getText().toString());
		// update controls state
		updateRepeatViewsState(iRepeatType);
	}

	public void setActivityTitle(String sSubTitle) {
		String sTitle = utils.getResStr(R.string.titleDefaultRepeat);
		if (sSubTitle.length() > 0)
			sTitle += ": " + sSubTitle;
		tvRepeatTitle.setText(sTitle);
	}

	private void initState() {

		setActivityTitle("");

		setRepeatType(iRepeatType);

		updateEveryValueView();
		updateEndOnDateView();
	}

	private void updateEveryValueView() {
		tvRepeatEveryValue.setText(Integer.toString(iRepeatEvery));
	}

	private void updateRepeatViewsState(int iRepeatType) {
		// change visibility of repeat views
		if (iRepeatType == 0) // none
		{
			llayAppointmentRepeatEvery.setVisibility(View.GONE);
			llayAppointmentRepeatEndOnDate.setVisibility(View.GONE);
			llayAppointmentRepeatEndOnDateLabel.setVisibility(View.GONE);
		} else {
			// yearly
			if (iRepeatType == 4) {
				llayAppointmentRepeatEvery.setVisibility(View.GONE);
			} else {
				llayAppointmentRepeatEvery.setVisibility(View.VISIBLE);
				llayAppointmentRepeatEndOnDate.setVisibility(View.VISIBLE);
				llayAppointmentRepeatEndOnDateLabel.setVisibility(View.VISIBLE);
			}
		}
	}

	private void updateEndOnDateView() {
		if (calRepeatEnd.getTimeInMillis() != 0) {
			btnEndOnDate.setText(utils.getLongDate(calRepeatEnd));
		} else {
			btnEndOnDate.setText(utils.getResStr(R.string.labNoEndDate));
		}
	}

	public static int getExtraRepeatType(Bundle extras) {
		return extras.getInt(DATAKEY_TYPE);
	}

	public static int getExtraRepeatEvery(Bundle extras) {
		return extras.getInt(DATAKEY_EVERY);
	}

	public static long getExtraRepeatEndOnDate(Bundle extras) {
		return extras.getLong(DATAKEY_ENDONDATE);
	}

	public static void openRepeatForEdit(Fragment parent, Bundle extras,
			int iRepeatType, int iEvery, long lEndOnDate) {
		extras.clear();
		extras.putBoolean("EditRepeat", true);
		extras.putInt(DATAKEY_TYPE, iRepeatType);
		extras.putInt(DATAKEY_EVERY, iEvery);
		extras.putLong(DATAKEY_ENDONDATE, lEndOnDate);
		
		Intent intent = new Intent("org.lansir.af.intent.action.ACTION_MODE_EDIT_ACTIVITYREPEAT");

		intent.putExtras(extras);
		
		parent.startActivityForResult(intent, SELECT_REPEAT_REQUEST);

	}

	public static boolean getActivityResult(int requestCode, int resultCode,
			Bundle extras) {
		if ((requestCode == SELECT_REPEAT_REQUEST) && (resultCode == RESULT_OK)) {
			if ((extras != null) && (extras.containsKey("EditRepeat"))) {
				return true;
			}
		}
		return false;
	}

	private void editDone() {
		Bundle bundleResult = new Bundle();
		bundleResult.putBoolean("EditRepeat", true);
		bundleResult.putInt(DATAKEY_TYPE, iRepeatType);
		bundleResult.putInt(DATAKEY_EVERY, iRepeatEvery);
		bundleResult.putLong(DATAKEY_ENDONDATE, calRepeatEnd.getTimeInMillis());

		Intent intentData = new Intent("");
		intentData.putExtras(bundleResult);
		this.setResult(RESULT_OK, intentData);

		finish();
	}

	
	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {

		@Override
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			calRepeatEnd = Calendar.getInstance();
			calRepeatEnd.set(Calendar.YEAR, year);
			calRepeatEnd.set(Calendar.MONTH, monthOfYear);
			calRepeatEnd.set(Calendar.DAY_OF_MONTH, dayOfMonth);
			if (calRepeatEnd.getTimeInMillis() != 0) {
				btnEndOnDate.setText(utils.getLongDate(calRepeatEnd));
			} else {
				btnEndOnDate.setText(utils.getResStr(R.string.labNoEndDate));
			}
		}

	};

}
